package study.alibaba.sentinel.support.rule;

import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.datasource.nacos.NacosDataSource;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.List;

@Slf4j
@Configuration
public class NacosRuleConfig {

    private String serverAddr = "101.42.254.155:8848";
    private String groupId = "DEFAULT_GROUP";
    private String dataId = "test-flow";

    @PostConstruct
    public void loadRules() {
        //
        ReadableDataSource<String, List<FlowRule>> dataSource = new NacosDataSource<>(serverAddr,
                groupId,
                dataId,
                source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {
                }));
        //
        FlowRuleManager.register2Property(dataSource.getProperty());
    }
}
